import { EditorView,keymap,ViewUpdate,highlightActiveLine } from "@codemirror/view"
import { EditorState } from "@codemirror/state"
import MittUtils from "./MittUtils"
import { MyTheme } from "./EditorTheme"
import { codeblock } from './codeblock';
import { markdown } from '@codemirror/lang-markdown';
import { javascriptLanguage } from '@codemirror/lang-javascript';
import {
  classHighlightStyle,
  defaultHighlightStyle,
} from '@codemirror/highlight';

export const createEditor = (options: { doc: string, parent: HTMLElement }) => {
    const editorView = new EditorView({
        state: EditorState.create({ 
            doc: options.doc,
            extensions: [
                MyTheme(),
                codeblock(),
                markdown({
                    defaultCodeLanguage: javascriptLanguage,
                    // Disable markdown keymaps.
                    addKeymap: false,
                  }),
                defaultHighlightStyle,
                classHighlightStyle,
                highlightActiveLine(),
                EditorView.updateListener.of((v:ViewUpdate) => {
                    if (v.docChanged) {
                        MittUtils.emit("change",{
                            doc: v.state.doc.toString(),
                            head: v.state.selection.main.head
                        })
                    }
                }) 
            ]
        }),
        parent: options.parent
    })
    return editorView;
}
